package org.apache.dolphinscheduler.api.utils;

import org.apache.dolphinscheduler.dao.entity.Schedule;
import org.apache.dolphinscheduler.dao.mapper.InputParamMapper;
import org.apache.dolphinscheduler.dao.mapper.OutputInfoMapper;
import org.apache.dolphinscheduler.dao.mapper.ScheduleMapper;
import org.apache.dolphinscheduler.dao.mapper.TaskInstanceMapper;
import org.apache.dolphinscheduler.service.memoryaddress.MemoryAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@EnableScheduling
public class TimingTask {
    @Autowired
    ScheduleMapper scheduleMapper;

    @Autowired
    MemoryAddressService memoryAddressService;

    @Autowired
    OutputInfoMapper outputInfoMapper;

    @Autowired
    TaskInstanceMapper taskInstanceMapper;

    @Autowired
    InputParamMapper inputParamMapper;

    /**
     * 定时删除调度执行的task
     */
    @Scheduled(cron = "0 50 23 * * ?")
    public void deleteTaskOnTime() {
        //获取运行状态为调度执行的processInstanceId
        List<Schedule> scheduleList = scheduleMapper.queryOnlineSchedule();

        for (int i = 0; i < scheduleList.size(); i++) {

            if (scheduleList.get(i).getOvertime() == 0) {
                continue;
            }
            List<Integer> taskInstanceIdList = taskInstanceMapper.queryTaskByProcessIdAndOvertime(scheduleList.get(i).getProcessInstanceId(), scheduleList.get(i).getOvertime());

            for (int i1 = 0; i1 < taskInstanceIdList.size(); i1++) {

                memoryAddressService.deleteByTaskInstanceId(taskInstanceIdList.get(i1));

                outputInfoMapper.delByTaskInstanceId(taskInstanceIdList.get(i1));

                taskInstanceMapper.deleteById(taskInstanceIdList.get(i1));

                inputParamMapper.deleteByNodeId(taskInstanceIdList.get(i1));
            }
        }
    }
}
